<template>
  <div class="manual-create">
    <!-- 左侧试卷信息 -->
    <div class="left-section">
      <el-affix :offset="60">
        <div class="paper-info">
          <div class="info-header">
            <h3>试卷信息</h3>
          </div>
          <div class="info-content">
            <el-form :model="paperForm" label-width="80px">
            <el-form-item label="试卷名称">
              <el-input v-model="paperForm.name" placeholder="请输入试卷名称"/>
            </el-form-item>
            <el-form-item label="学科">
              <el-select v-model="paperForm.subjectId" placeholder="请选择学科">
                <el-option v-for="subject in subjects" :key="subject.id" :label="subject.name" :value="subject.id"/>
              </el-select>
            </el-form-item>
            <el-form-item label="试卷编号">
              <el-radio-group v-model="paperForm.numberType">
                <el-radio label="auto">连续编号</el-radio>
                <el-radio label="custom">按规则编号</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- <el-form-item label="题型设置">
              <el-radio-group v-model="paperForm.typeSet">
                <el-radio label="auto">按题型分类</el-radio>
                <el-radio label="custom">不按题型分类</el-radio>
              </el-radio-group> -->
            <!-- </el-form-item> -->
            <el-form-item label="试卷难度">
              <el-select v-model="paperForm.difficulty" placeholder="请选择难度">
                <el-option label="简单" value="easy"/>
                <el-option label="中等" value="medium"/>
                <el-option label="困难" value="hard"/>
              </el-select>
            </el-form-item>
          </el-form>
          </div>
          <!-- 题目导航 -->
          <div class="question-nav">
            <div class="nav-header">
              <h3>题目导航</h3>
            </div>
            <div class="nav-content">
              <template v-for="type in questionTypes" :key="type.value">
                <div v-if="getQuestionsByType(type.value).length > 0" class="nav-section">
                  <div class="nav-type">{{ type.label }}</div>
                  <div class="nav-items">
                    <el-tag
                      v-for="(question, index) in getQuestionsByType(type.value)"
                      :key="question.id"
                      :type="getDifficultyTag(question.difficulty)"
                      effect="light"
                      size="small"
                      class="nav-item"
                    >
                      {{ index + 1 }}
                    </el-tag>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </el-affix>
    </div>

    <!-- 中间题目编辑区 -->
    <div class="question-edit">
      <div class="edit-header">
        <h3>试卷内容</h3>
        <div class="edit-actions">
          <el-button type="primary" @click="handlePreview">预览试卷</el-button>
          <el-button type="success" @click="handleSave">保存试卷</el-button>
        </div>
      </div>
      <div class="questions-container">
        <template v-if="sortedQuestions.length > 0">
          <question-list :questions="sortedQuestions" @edit="handleEdit" @delete="handleRemove" :disabled="true"/>
        </template>
        <el-empty v-else description="暂无题目,请从右侧题库选择或手动添加题目"/>
      </div>
    </div>

    <!-- 右侧题库选择区 -->
    <div class="right-section">
      <el-affix :offset="60">
        <div class="question-bank">
          <div class="bank-header">
            <h3>题库选择</h3>
            <el-button type="primary" @click="handleAddQuestion">
              <el-icon><Plus /></el-icon>新增题目
            </el-button>
          </div>
          <div class="bank-filter">
            <el-select v-model="selectedSubject" placeholder="选择学科" @change="handleSubjectChange">
              <el-option v-for="subject in subjects"
                         :key="subject.id"
                         :label="subject.name"
                         :value="subject.id"/>
            </el-select>
            <el-select v-model="selectedLibrary" placeholder="选择题库">
              <el-option v-for="library in libraries"
                         :key="library.id"
                         :label="library.name"
                         :value="library.id"/>
            </el-select>
          </div>
          <div class="bank-search">
            <el-input v-model="searchKeyword" 
                      placeholder="搜索题目" 
                      clearable
                      @input="handleSearch">
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="bank-questions">
            <el-scrollbar height="calc(100vh - 300px)">
              <div v-for="question in filteredQuestions" 
                   :key="question.id" 
                   class="bank-question-item"
                   @click="handleSelectQuestion(question)">
                <div class="question-brief">
                  <el-tag size="small" :type="getQuestionTypeTag(question.questionType)">
                    {{ getQuestionTypeLabel(question.questionType) }}
                  </el-tag>
                  <template v-if="question.questionType === 'READING'">
                    <span class="question-text">{{ question.passage }}</span>
                  </template>
                  <template v-else>
                    <span class="question-text">{{ question.stem }}</span>
                  </template>
                </div>
              </div>
            </el-scrollbar>
          </div>
        </div>
      </el-affix>
    </div>

    <!-- 编辑抽屉 -->
    <el-drawer v-model="drawerVisible"
              :title="editingQuestion.id ? '编辑题目' : '新增题目'"
              direction="rtl"
              size="40%">
      <question-edit :question="editingQuestion"                   
                    @save="handleQuestionSave"
                    @cancel="drawerVisible = false"/>
    </el-drawer>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="试卷预览"
      width="80%"
      :destroy-on-close="true"
    >
      <paper-preview 
        :paper="paperForm" 
        :questions="sortedQuestions"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handleSave">保存试卷</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getSubjects } from '../../../api/subject'
import { getLibrariesBySubject } from '../../../api/library'
import { getLibraryQuestions, saveQuestions, updateQuestion,getQuestions } from '../../../api/question'
import QuestionEdit from '../../../components/question/QuestionEdit.vue'
import PaperPreview from '../../../components/paper/PaperPreview.vue'  // 导入预览组件
import { savePaper, getPaperById, updatePaper } from '../../../api/paper'
import { useRoute, useRouter } from 'vue-router'

// 添加 router
const router = useRouter()

// 试卷表单数据
const paperForm = ref({
  paperId: '',
  name: '',
  numberType: 'auto',
  typeSet: 'auto',
  difficulty: 'medium',
  subjectId: ''
})

// 选中的题目列表
const selectedQuestions = ref([])

// 题库相关数据
const subjects = ref([])
const libraries = ref([])
const selectedSubject = ref('')
const selectedLibrary = ref('')
const searchKeyword = ref('')
const bankQuestions = ref([])

// 编辑相关
const drawerVisible = ref(false)
const editingQuestion = ref({})

// 预览对话框
const previewDialogVisible = ref(false)

// 获取学科列表
const fetchSubjects = async () => {
  try {
    const userId = JSON.parse(localStorage.getItem('user')).id
    const res = await getSubjects(userId, 1, 100)
    subjects.value = res.data.list
  } catch (error) {
    ElMessage.error('获取学科列表失败')
  }
}

// 获取题库列表
const handleSubjectChange = async (subjectId) => {
  selectedLibrary.value = ''
  if (subjectId) {
    try {
      const res = await getLibrariesBySubject(subjectId, 1, 100)
      libraries.value = res.data.list
    } catch (error) {
      ElMessage.error('获取题库列表失败')
    }
  } else {
    libraries.value = []
  }
}

// 获取题库中的题目
const fetchLibraryQuestions = async () => {
  if (!selectedLibrary.value) return
  try {
    const res = await getLibraryQuestions(selectedLibrary.value)
    bankQuestions.value = res.data
  } catch (error) {
    ElMessage.error('获取题目列表失败')
  }
}
watch(selectedLibrary, () => {
  fetchLibraryQuestions()
})
// 根据关键词筛选题目
const filteredQuestions = computed(() => {
  if (!searchKeyword.value) return bankQuestions.value
  return bankQuestions.value.filter(question => 
    question.stem.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 处理题目选择
const handleSelectQuestion = (question) => {
  selectedQuestions.value.push({...question})
  ElMessage.success('已添加到试卷')
}
// 处理题目移除
const handleRemove = (index) => {
  console.log("index===>",index)
  // 找到要移除的题目索引
  const indexToRemove = selectedQuestions.value.findIndex(question => question.id === index.id);
  // splice 是一个原地修改数组的方法，它的第一个参数是起始索引，第二个参数是要删除的元素个数。
  selectedQuestions.value.splice(indexToRemove, 1)
}

// 处理题目编辑
const handleEdit = (question) => {
  editingQuestion.value = {...question}
  drawerVisible.value = true
}

// 处理新增题目
const handleAddQuestion = () => {
  editingQuestion.value = {
    questionType: 'SINGLE_CHOICE',
    difficulty: 1,
    options: [],
    answers: []
  }
  drawerVisible.value = true
}

// 处理题目保存
const handleQuestionSave = async (question) => {
  if (question.id) {
    // 更新已有题目
    const index = selectedQuestions.value.findIndex(q => q.id === question.id)
    if (index !== -1) {
      selectedQuestions.value[index] = {...question}
    }
    const data = JSON.stringify(question)
    await updateQuestion(question.id, data)
  } else {
    // 添加新题目
    // const res = await saveQuestions("paper",JSON.stringify([question]))
    const res = await saveQuestions("paper",JSON.stringify([question]))
    if (res.data && res.data.length > 0) {
      question.id = res.data[0]
      selectedQuestions.value.push({...question})
    }
  }
  drawerVisible.value = false
  ElMessage.success('保存成功')
}

// 预览试卷
const handlePreview = () => {
  if (!paperForm.value.name) {
    ElMessage.warning('请输入试卷名称')
    return
  }
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning('请添加试题')
    return
  }
  previewDialogVisible.value = true
}

// 保存试卷
const handleSave = async () => {
  if (!paperForm.value.name) {
    ElMessage.warning('请输入试卷名称')
    return
  }
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning('请添加试题')
    return
  }

  try {
    // 准备所有题型
    const allTypes = new Set()
    selectedQuestions.value.forEach(q => {
      allTypes.add(q.questionType)
    })
    
    const paperData = {
      paperId: paperForm.value.paperId || null,
      userId: JSON.parse(localStorage.getItem('user')).id,
      subjectId: paperForm.value.subjectId,
      paperName: paperForm.value.name,
      questionIds: selectedQuestions.value.map(q => q.id).join(','),
      typeSet: Array.from(allTypes).join(','),
      difficulty: paperForm.value.difficulty,
      numberType: paperForm.value.numberType,
    }

    let res
    if (paperForm.value.paperId) {
      res = await updatePaper(paperData)
    } else {
      res = await savePaper(paperData)
    }
    
    if (res.code === 200) {
      ElMessage.success('保存成功')
      router.push('/paper/list')
    } else {
      ElMessage.error(res.data.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存试卷失败:', error)
    ElMessage.error('保存失败')
  }
}

// 工具函数
const getQuestionTypeTag = (type) => {
  const typeMap = {
    'SINGLE_CHOICE': 'primary',
    'MULTIPLE_CHOICE': 'success',
    'TRUE_FALSE': 'info',
    'FILL_BLANK': 'warning',
    'SHORT_ANSWER': 'danger',
    'READING': 'danger'
  }
  return typeMap[type] || 'info'
}

const getQuestionTypeLabel = (type) => {
  const typeMap = {
    'SINGLE_CHOICE': '单选题',
    'MULTIPLE_CHOICE': '多选题',
    'TRUE_FALSE': '判断题',
    'FILL_BLANK': '填空题',
    'SHORT_ANSWER': '简答题',
    'READING': '阅读理解'
  }
  return typeMap[type] || type
}

const getDifficultyTag = (difficulty) => {
  const difficultyMap = {
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return difficultyMap[difficulty] || 'info'
}

const getDifficultyLabel = (difficulty) => {
  const difficultyMap = {
    1: '简单',
    2: '中等',
    3: '困难'
  }
  return difficultyMap[difficulty] || '未知'
}

// 修改getQuestionsByType方法，添加排序功能
const getQuestionsByType = (type) => {
  const questions = selectedQuestions.value.filter(q => q.questionType === type)
  // 按照题目难度和分数排序
  return questions.sort((a, b) => {
    // 先按难度排序
    if (a.difficulty !== b.difficulty) {
      return a.difficulty - b.difficulty
    }
    // 难度相同按分数排序
    return (b.score || 0) - (a.score || 0)
  })
}

// 添加计算属性，用于按题型排序的题目列表
const sortedQuestions = computed(() => {
  if (paperForm.value.numberType === 'auto') {
    // 按题型分类并排序
    return questionTypes.reduce((acc, type) => {
      const questions = getQuestionsByType(type.value)
      return [...acc, ...questions]
    }, [])
  } else {
    // 不按题型分类，仅按难度和分数排序
    return [...selectedQuestions.value].sort((a, b) => {
      if (a.difficulty !== b.difficulty) {
        return a.difficulty - b.difficulty
      }
      return (b.score || 0) - (a.score || 0)
    })
  }
})

// 题目类型选项
const questionTypes = [
  { value: 'SINGLE_CHOICE', label: '一、单选题' },
  { value: 'MULTIPLE_CHOICE', label: '二、多选题' },
  { value: 'TRUE_FALSE', label: '三、判断题' },
  { value: 'FILL_BLANK', label: '四、填空题' },
  { value: 'SHORT_ANSWER', label: '五、简答题' },
  { value: 'READING', label: '六、阅读理解' }
]
const route = useRoute()
// 页面加载时获取数据
onMounted(() => {
  fetchSubjects()
  if(route.query.paperId){
    getPaperInfo(route.query.paperId)
  }
})
const getPaperInfo = async (paperId) => {
  const res = await getPaperById(paperId)
  console.log(res)
  if(res.code === 200){
    paperForm.value.paperId = res.data.userId
    paperForm.value.name = res.data.paperName
    paperForm.value.subjectId = res.data.subjectId
    paperForm.value.numberType = res.data.numberType
    paperForm.value.typeSet = res.data.typeSet
    paperForm.value.difficulty = res.data.difficulty
    const questionIds = res.data.questionIds.split(',')
    const questionList = await getQuestions(questionIds)
    selectedQuestions.value = questionList.data
  }
}
</script>

<style scoped>
.manual-create {
  display: grid;
  grid-template-columns: 250px 1fr 300px;
  gap: 20px;
  padding: 20px;
  min-height: calc(100vh - 100px);
}

.left-section,
.right-section {
  position: relative;
}

/* 左侧试卷信息样式 */
.paper-info {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  max-height: calc(100vh - 40px);
  overflow-y: auto;
}

.info-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

/* 中间题目编辑区样式 */
.question-edit {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 140px);
}

.edit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.questions-container {
  flex: 1;
  overflow-y: auto;
  padding-right: 10px;
}

.question-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;
}

.question-actions {
  margin-left: auto;
}

/* 右侧题库选择区样式 */
.question-bank {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  max-height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

.bank-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.bank-filter {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 15px;
}

.bank-search {
  margin-bottom: 15px;
}

.bank-questions {
  flex: 1;
  overflow: hidden;
}

.bank-question-item {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: background-color 0.3s;
}

.bank-question-item:hover {
  background-color: #f5f7fa;
}

.question-brief {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.question-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

::-webkit-scrollbar-track {
  background-color: #f5f7fa;
}

/* 预览样式 */
.preview-content {
  padding: 20px;
}

.paper-header {
  text-align: center;
  margin-bottom: 30px;
}

.paper-header h1 {
  margin-bottom: 15px;
}

.paper-info {
  /* display: flex; */
  justify-content: center;
  gap: 20px;
  color: #666;
}

.questions-preview {
  max-height: calc(100vh - 300px);
  overflow-y: auto;
  padding-right: 10px;
}

.question-type-section {
  margin-bottom: 30px;
}

.question-type-section h3 {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409EFF;
}

.preview-question-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.preview-question-item .question-header {
  margin-bottom: 10px;
}

.preview-question-item .question-score {
  color: #f56c6c;
  margin-left: 10px;
}

.question-nav {
        margin-top: 20px;
        padding: 15px;
        border-top: 1px solid #ebeef5;
      }

      .nav-header {
        margin-bottom: 15px;
      }

      .nav-section {
        margin-bottom: 15px;
      }

      .nav-type {
        font-size: 14px;
        color: #606266;
        margin-bottom: 8px;
      }

      .nav-items {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
      }

      .nav-item {
        cursor: pointer;
      }
</style>